package com.xiaobao.campusLostFoundAfter.controller;

import com.xiaobao.campusLostFoundAfter.common.Result;
import com.xiaobao.campusLostFoundAfter.pojo.User;
import com.xiaobao.campusLostFoundAfter.service.UserService;
import com.xiaobao.campusLostFoundAfter.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

//  登录控制器
@RestController
public class loginController {
    private static final Logger log = LoggerFactory.getLogger(loginController.class);
    private final UserService userService;

    public loginController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    //根据用户id和密码进行登录
    public Result<Map<String, String>> login(String userId, String password) {
        log.info("用户id：{}，密码：{}", userId, password);
        Map<String, String> map = new HashMap<>();
        try {
            User userDB = userService.getUserById(userId).getData();
            if (userDB == null) {
                return Result.error("用户不存在或账号密码错误");
            } else {
                Map<String, String> payload = new HashMap<>();
                payload.put("userId", userDB.getUserId());
                payload.put("name", userDB.getName());
                // 生成jwt令牌
                String token = JWTUtils.getToken(payload);
                map.put("state", String.valueOf(true));
                map.put("msg", "认证成功！");
                map.put("userId", userDB.getUserId());
                map.put("token", token);  // 响应token
            }
        } catch (Exception e) {
            map.put("state", String.valueOf(false));
            map.put("msg", e.getMessage());
        }
        return Result.success(map);
    }
}
